package c.x.jy.service.service.impl;

import c.x.jy.common.utils.Constant;
import c.x.jy.dao.dao.SysUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import c.x.jy.common.utils.PageUtils;
import c.x.jy.common.utils.Query;

import c.x.jy.dao.dao.SysRoleDao;
import c.x.jy.dao.entity.SysRoleEntity;
import c.x.jy.dao.entity.SysUserEntity;
import c.x.jy.service.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;

@CacheConfig(cacheNames = { "user" })
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
    @Autowired
    private SysUserDao sysUserDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        	QueryWrapper<SysRoleEntity> query= 	 new QueryWrapper<SysRoleEntity>() ;
    	if(params.get("searchKey")!=null&&params.get("searchValue")!=null&&!StringUtils.isEmpty(params.get("searchKey").toString())&&!StringUtils.isEmpty(params.get("searchValue").toString()))
    	    query.eq(  params.get("searchKey").toString(), params.get("searchValue"));
        if(params.get("businessId")!=null) 	query.eq("business_id", params.get("businessId"));
        IPage<SysRoleEntity> page = this.page(
                new Query<SysRoleEntity>().getPage(params),
                 query
        );

        return new PageUtils(page);
    }
    @Cacheable(key = " 'roles:'+ methodName+':' +#p0  ",unless="#result == null")
	@Override
	public Set<String> selectRolesByUserId(Long userId) {
        QueryWrapper<SysRoleEntity> query=	new QueryWrapper<SysRoleEntity>();
        SysUserEntity user = sysUserDao.selectById(userId);
        userId=(user.getBusinessId()== Constant.SUPER_ADMIN)?null: userId;
        if(userId!=null) {
            query .eq("sru.user_id", userId);
        }
        return this.getBaseMapper().selectSetListRolesByUserId(query);
	}
    @Cacheable(key = " 'roles:'+ methodName+':' +#p0.userId+':' +#p0.businesstype ",unless="#result == null")
    @Override
    public List<SysRoleEntity> selectRolesByUserId(SysUserEntity user) {
        QueryWrapper<SysRoleEntity> query=	new QueryWrapper<>();
        if(user.getUserId()!=null)  	query .eq("sru.user_id", user.getUserId());
        return this.getBaseMapper().selectRolesByUserId(query);
    }

}
